package controllers;

import java.util.ArrayList;
import java.util.List;

import models.Dream;
import models.Keyword;
import models.Proposal;
import play.mvc.Controller;
import play.i18n.Messages;
import play.data.validation.Validation;
import play.data.validation.Valid;

public class Proposals extends Controller {
    public static void index() {
        List<Proposal> entities = models.Proposal.all().fetch();
        render(entities);
    }

    public static void create(Proposal entity) {
        render(entity);
    }

    public static void show(java.lang.Long id) {
        Proposal entity = Proposal.findById(id);
        renderJSON(entity);
    }

    public static void edit(java.lang.Long id) {
        Proposal entity = Proposal.findById(id);
        render(entity);
    }

    public static void delete(java.lang.Long id) {
        Proposal entity = Proposal.findById(id);
        entity.delete();
        index();
    }
    
    public static void save(@Valid Proposal entity) {
        if (validation.hasErrors()) {
            flash.error(Messages.get("scaffold.validation"));
            render("@create", entity);
        }
        entity.save();
        flash.success(Messages.get("scaffold.created", "Proposal"));
        index();
    }

    public static void update(@Valid Proposal entity) {
        if (validation.hasErrors()) {
            flash.error(Messages.get("scaffold.validation"));
            render("@edit", entity);
        }
        
        entity = entity.merge();
        
        entity.save();
        flash.success(Messages.get("scaffold.updated", "Proposal"));
        index();
    }
    
    public static void indexByDream(Dream dream){
    	List<Proposal> allProposals = Proposal.findAll();
    	
    	List<Proposal> indexedProposals = new ArrayList<Proposal>();
    	for (Proposal proposal : allProposals) {
			if(proposal.dream.id.equals(dream.id)){
				indexedProposals.add(proposal);
			}
		}
    	
    	renderJSON(indexedProposals);
    }    
}
